<?php

namespace App\Http\Controllers;

use App\Models\Position;
use App\Repositories\PositionRepository;
use App\Http\Requests\Logic\Position\QueryResource;
use App\Http\Requests\Logic\Position\StoreResource;
use App\Http\Requests\Logic\Position\UpdateResource;
use App\Http\Requests\Logic\Position\QueryCollection;
use App\Http\Requests\Logic\Position\DestroyResource;

/**
 * 岗位管理逻辑控制器
 *
 * Date: 02/05/2018
 * @author George
 * @package App\Http\Controllers
 */
class PositionController extends Controller
{
	protected $positionRepository;

	/**
	 * PositionController constructor.
	 * @param PositionRepository $positionRepository
	 */
	public function __construct(PositionRepository $positionRepository)
	{
		$this->positionRepository = $positionRepository;
	}

	/**
	 * 获取岗位信息
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param QueryCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(QueryCollection $request)
	{
		$department_id = $request->get('department_id');
		$name = $request->get('name');

		if ($department_id) {
			$positions = $this->positionRepository->getByDepartment($department_id, $name);
		} else {
			$positions = $this->positionRepository->getByCompany($request->user()->company_id, $name);
		}
		return success($positions);
	}

	/**
	 * 获取岗位详情
	 *
	 * Date: 24/04/2018
	 * @author George
	 * @param QueryResource $request
	 * @param Position $position
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(QueryResource $request, Position $position)
	{
		return success($position);
	}

	/**
	 * 创建岗位
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
	public function store(StoreResource $request)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());
		$position = $this->positionRepository->store($attributes);
		return stored($position);
	}

	/**
	 * 更新岗位信息
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param UpdateResource $request
	 * @param Position $position
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(UpdateResource $request, Position $position)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());
		$position->update($attributes);
		return updated($position);
	}

	/**
	 * 删除岗位
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param DestroyResource $request
	 * @param Position $position
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(DestroyResource $request, Position $position)
	{
		$position->delete();
		return deleted();
	}
}
